package com.gambi.example.tapestry.components.chatter;

import org.apache.tapestry5.ComponentResources;
import org.apache.tapestry5.annotations.IncludeJavaScriptLibrary;
import org.apache.tapestry5.annotations.Log;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.ioc.annotations.Inject;

import com.gambi.example.client.GWTUI;
import com.gambi.example.client.chatter.model.Contact;
import com.gambi.example.client.chatter.model.Message;
import com.gambi.example.client.chatter.services.MessengerService;
import com.gambi.example.tapestry.components.GWTComponent;

/*
 * TODO This is the back end component of the MessageService RemoteService from GWT. It should implement the MessageService interface.
 * For us it can be also listen for the corresponding events.
 * TODO All the code here must be refactored in a service that is injected. The service manages all the connected users ad works like an event bus method.
 * In also manages the thread pool that is used to maintaing the hanging requests... Possibly without interfere to much with Tapestry.
 */
@IncludeJavaScriptLibrary(value = { "context:js/gwtjs/com.gambi.example.GWTUI/com.gambi.example.GWTUI.nocache.js" })
public class Chatter extends GWTComponent<GWTUI, MessengerService> {

	@Inject
	private MessengerService messengerService;

	@Inject
	private ComponentResources componentResources;

	// TODO Cannot make it working with void ...
	@Log
	@OnEvent("signin")
	public void signIn(String name) {
		System.out.println("Chatter.signIn() name = " + name);
		messengerService.signIn(name);
	}

	@Log
	@OnEvent("signout")
	public boolean signOut() {
		messengerService.signOut();
		return true;
	}

	@Log
	@OnEvent("sendmessage")
	public boolean sendMessage(Contact to, Message message) {
		messengerService.sendMessage(to, message);
		return false;
	}

	@Log
	@OnEvent("getevents")
	public Object getEvents() {
		System.out.println("Chatter.getEvents()");
		return messengerService.getEvents();
	}

	public String getSignInEventLink() {
		return componentResources.createEventLink("signin", new Object[] {})
				.toAbsoluteURI();
	}

	public String getSignOutEventLink() {
		return componentResources.createEventLink("signout", new Object[] {})
				.toAbsoluteURI();
	}

	public String getSendMessageEventLink() {
		return componentResources.createEventLink("sendmessage",
				new Object[] {}).toAbsoluteURI();
	}

	public String getGetEventsEventLink() {
		return componentResources.createEventLink("getevents", new Object[] {})
				.toAbsoluteURI();
	}

	public Class<GWTUI> getGWTModuleClass() {
		return GWTUI.class;
	}

}
